<script setup lang="ts">
import { ref,onMounted,onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCurrentUserStore } from '@/modules/security/stores/currentUserStores';
import { webSocketStore } from '@/modules/socket/stores/webSocket';
import { securityApi } from '@/modules/security/api'

const router = useRouter()
const userStore = useCurrentUserStore()
const wsSession = webSocketStore()
// 获取路由列表
const routes = router.getRoutes().filter(route => route.name === 'portal')[0].children.filter(route => route.name !== 'portalHome')

// 进入页面首先获取当前用户信息
onMounted(async () => {
  if(userStore.isLoggedIn()){
    if(!(userStore.currentUser && userStore.currentUser.user && userStore.currentUser.user.username)){
      try {
        await securityApi.userInfo().then(res => {
          userStore.setUser(res.data);
        })
      } catch (error) {
        console.error('获取信息失败 :', error);
        userStore.clearUser()
      }
    }
    if(userStore.currentUser && userStore.currentUser.user && userStore.currentUser.user.username){
      if(!(wsSession.session?.wsConnected)){
        wsSession.connectWebSocket();
      }
      const receivedData = ref<string>('');
      wsSession.subMessage(
        '/portal',
        (message: string) => {
          receivedData.value = message;
        }
      )
    }
  }
});
onUnmounted(() => {
  wsSession.unSubMessage('/portal')
});
</script>

<template>
  <div class="max">
    <header class="nav">
      <div class="container">
        <h1 class="logo">
          <router-link to="/">泡泡站</router-link>
        </h1>
        <ul>
          <li v-for="route in routes" :key="route.path">
            <router-link :to="route.path">{{ route.meta?.name }}</router-link>
          </li>
          <li>
            <router-link to="/admin">管理端</router-link>
          </li>
        </ul>
      </div>
    </header>
    <div>
      <router-view></router-view>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  max-width: 1200px;
  margin: 0 auto;
}

.nav {
  background-color: #222;
  top: 0;
  left: 0;
  right: 0;
  transition: all 0.3s ease-in-out;
}

.nav .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  transition: all 0.3s ease-in-out;
}

.nav ul {
  display: flex;
  list-style-type: none;
  align-items: center;
  justify-content: center;
}

.nav a {
  color: #fff;
  text-decoration: none;
  padding: 7px 15px;
  transition: all 0.3s ease-in-out;
}

.nav.active {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.nav.active a {
  color: #000;
}

.nav.active .container {
  padding: 10px 0;
}

.nav a.current,
.nav a:hover {
  color: #c0392b;
  font-weight: bold;
}
</style>
